<?php
include_once('config/config.php');

// 判断是否登录函数
$LoginAdmin = checkAuth();

// 判断是否有post请求
if ($_POST) {
    // 接收参数
    $action = $_POST['action'];

    // 查询部门数据
    if ($action == 'depid') {
        // 组装sql语句
        $sql = "SELECT * FROM `pre_department` ORDER BY `id` ASC";

        $DepData = findAll($sql);
        // 返回数据
        if ($DepData) {
            echo json_encode([
                'code' => 1,
                'msg' => '查询部门数据成功',
                'data' => $DepData
            ]);
            exit;
        } else {
            echo json_encode([
                'code' => 0,
                'msg' => '查询部门数据失败',
                'data' => []
            ]);
            exit;
        }
    }


    // 查询职位数据
    if ($action == 'jobid') {
        $depid = $_POST['depid'] ?? 0;

        $JobData = findAll("SELECT * FROM `pre_job`  WHERE `depid` = '$depid'  ORDER BY `id` ASC");
        // 返回数据
        if ($JobData) {
            echo json_encode([
                'code' => 1,
                'msg' => '查询职位数据成功',
                'data' => $JobData
            ]);
            exit;
        } else {
            echo json_encode([
                'code' => 0,
                'msg' => '查询职位数据失败',
                'data' => []
            ]);
            exit;
        }
    };

    // var_dump($_POST);
    // exit;

    // 把提交过来的数据封装成数组
    $data = [
        'name' => $_POST['name'],
        'mobile' => $_POST['mobile'],
        'email' => $_POST['email'],
        'sex' => $_POST['sex'],
        'address' => $_POST['address'],
        'depid' => $_POST['depid'],
        'jobid' => $_POST['jobid']
    ];

    // 处理地区数据
    if (!empty($_POST['code'])) {

        $code = $_POST['code'];

        $pathStr = find("SELECT `parentpath` FROM `pre_region` WHERE `code` = '$code'");

        if (!$pathStr) {
            showMsg('所选地区不存在');
        }

        // 字符串转数组
        $pathStr = explode(',', $pathStr['parentpath']);

        // 赋值
        $data['province'] = $pathStr[0] ?? null;
        $data['city'] = $pathStr[1] ?? null;
        $data['district'] = $pathStr[2] ?? null;
        
    }

    // 


    // 处理上传头像
    $res = build_upload('avatar');

    if ($res['code'] == 0) {
        showMsg($res['msg']);
    }


    // 封装数据
    $data['avatar'] = $res['data'] ?? null;
    // print_r($data);
    // exit;

    // 添加数据并且把添加的时间加进去
    $data['createtime'] = time();
    $result = add('person', $data);

    if ($result['code'] === 1) {
        showMsg('添加成功', 'presonList.php');
    } else {
        @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);
        echo $result['data'];
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php'); ?>
    <link rel="stylesheet" href="/assets/lib/city-picker/city-picker.css">
</head>
<style>
    .region {
        position: relative;
        width: 530px;
    }

    .address {
        margin-top: 50px;
    }
</style>

<body>

    <?php include_once('common/header.php'); ?>

    <?php include_once('common/menu.php'); ?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">添加用户</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="presonList.php">presonList</a> <span class="divider">/</span></li>
            <li class="active">presonAdd</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">

                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='presonList.php'"><i class="icon-list"></i> 管理员列表</button>
                    <div class="btn-group">
                    </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane active in" id="home">
                            <form method="post" enctype="multipart/form-data">

                                <label>员工姓名</label>
                                <input type="text" name="name" placeholder="请输入员工姓名" id="name" required class="input-xxlarge">

                                <label>手机号</label>
                                <input type="text" name="mobile" placeholder="请输入手机号" id="mobile" required class="input-xxlarge">

                                <label>邮箱</label>
                                <input type="email" name="email" placeholder="请输入邮箱" id="email" required class="input-xxlarge">

                                <label>性别</label>
                                <select name="sex" id="sex" class="input-xlarge">
                                    <option value="保密">保密</option>
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>

                                <div class="form-group region">
                                    <label for="region">选择地区</label>
                                    <input type="text" data-toggle="city-picker" name="region" id="region" value="" class="form-control input-xxlarge">
                                    <input type="hidden" name="code" id="code">
                                </div>

                                <div class="address">
                                    <label>详细地址</label>
                                    <input type="text" name="address" id="address" placeholder="请输入详细地址" required class="input-xxlarge">
                                </div>

                                <label>部门</label>
                                <select name="depid" id="depid" class="input-xlarge">
                                    <option value="0">请选择</option>

                                </select>

                                <label>职位</label>
                                <select name="jobid" id="jobid" class="input-xlarge">
                                    <option value="0">请选择</option>

                                </select>


                                <label>头像</label>
                                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                                <img src="/assets/images/upload.png" style="width: 200px;height:200px" id="img" alt="">

                                <label></label>
                                <input class="btn btn-primary" type="submit" id="submit" value="提交" />
                            </form>
                        </div>
                    </div>
                </div>

                <?php include_once('common/footer.php'); ?>

            </div>
        </div>
    </div>

</body>

</html>

<?php include_once('common/script.php'); ?>
<script src="/assets/lib/city-picker/city-picker.data.min.js"></script>
<script src="/assets/lib/city-picker/city-picker.min.js"></script>

<script>
    // 点击图片等于点击上传框
    $('#img').click(function() {
        $('#avatar').click();
    });

    // 监听上传框的值有变化时触发事件
    $('#avatar').change(function() {
        let file = $(this)[0].files[0];


        if (file) {
            // 创建一个FileReader对象,
            // 该对象是用来读取文件中的数据的
            let Reader = new FileReader();
            // 读取文件中的数据,方法会将文件转换为DataURL格式，这是一种将文件内容编码为URL的字符串表示形式的方法。
            Reader.readAsDataURL(file);

            // 读取操作完成后会触发onload事件（当reader加载完，触发事件）
            Reader.onload = function() {
                $('#img').attr('src', Reader.result);
            }

        }
    });

    // 查询部门
    (function() {
        $.ajax({
            type: 'post',
            url: 'presonAdd.php',
            data: {
                action: 'depid'
            },
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {

                    let temp = '';

                    for (let item of res.data) {
                        temp += `<option value="${item.id}">${item.name}</option>`
                    }

                    $('#depid').html(temp);

                    let depid = res.data[0].id ? res.data[0].id : '';

                    getjobData(depid);
                }
            }
        });
    })();

    function getjobData(depid) {
        $.ajax({
            type: 'post',
            url: 'presonAdd.php',
            data: {
                action: 'jobid',
                depid
            },
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {

                    let temp = '';

                    for (let item of res.data) {
                        temp += `<option value="${item.id}">${item.name}</option>`
                    }
                    $('#jobid').html(temp);
                }
            }
        });
    };

    // 选择部门时更新
    $('#depid').change(function() {
        let depid = $(this).val();
        getjobData(depid);
    });

    // 选择地区
    $("#region").on("cp:updated", function() {
        var citypicker = $(this).data("citypicker");
        var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
        $("#code").val(code);
    });
</script>